/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.FaceDraftDto;
import com.yami.shop.bean.model.FaceDraft;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.FaceDraftService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 草稿单接口
 * @author AI Assistant
 */
@RestController
@RequestMapping("/p/faceDraft")
@Tag(name = "草稿单接口")
public class FaceDraftController {

    @Autowired
    private FaceDraftService faceDraftService;

    /**
     * 获取草稿单列表（分页）
     */
    @GetMapping("/page")
    @Operation(summary = "获取草稿单列表" , description = "分页获取草稿单列表")
    @Parameter(name = "status", description = "状态（1:草稿, 2:已保存为设计稿）", required = false)
    public ServerResponseEntity<IPage<FaceDraftDto>> page(
            @RequestParam(value = "status", required = false) Integer status,
            PageParam<FaceDraft> page) {

        String userIdStr = SecurityUtils.getUser().getUserId();
        IPage<FaceDraft> faceDraftPage = faceDraftService.pageByUserIdAndStatus(page, userIdStr, status);
        IPage<FaceDraftDto> faceDraftDtoPage = faceDraftPage.convert(faceDraft -> {
            FaceDraftDto faceDraftDto = BeanUtil.copyProperties(faceDraft, FaceDraftDto.class);
            return faceDraftDto;
        });

        return ServerResponseEntity.success(faceDraftDtoPage);
    }

    /**
     * 获取草稿单列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取草稿单列表" , description = "获取草稿单列表")
    @Parameter(name = "status", description = "状态（1:草稿, 2:已保存为设计稿）", required = false)
    public ServerResponseEntity<List<FaceDraftDto>> list(
            @RequestParam(value = "status", required = false) Integer status) {

        String userIdStr = SecurityUtils.getUser().getUserId();
        List<FaceDraft> faceDraftList = faceDraftService.listByUserIdAndStatus(userIdStr, status);
        List<FaceDraftDto> faceDraftDtoList = BeanUtil.copyToList(faceDraftList, FaceDraftDto.class);

        return ServerResponseEntity.success(faceDraftDtoList);
    }

    /**
     * 获取草稿单详情
     */
    @GetMapping("/info")
    @Operation(summary = "获取草稿单详情" , description = "根据草稿单ID获取详情")
    @Parameter(name = "draftId", description = "草稿单ID", required = true)
    public ServerResponseEntity<FaceDraftDto> info(@RequestParam("draftId") Long draftId) {

        String userId = SecurityUtils.getUser().getUserId();
        FaceDraft faceDraft = faceDraftService.getById(draftId);
        if (faceDraft == null) {
            return ServerResponseEntity.success();
        }

        // 校验用户权限
        if (!faceDraft.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限查看该草稿单");
        }

        FaceDraftDto faceDraftDto = BeanUtil.copyProperties(faceDraft, FaceDraftDto.class);
        return ServerResponseEntity.success(faceDraftDto);
    }

    /**
     * 创建草稿单
     */
    @PostMapping("/save")
    @Operation(summary = "创建草稿单" , description = "创建新的草稿单")
    public ServerResponseEntity<Void> save(@RequestBody FaceDraftDto faceDraftDto) {
        String userId = SecurityUtils.getUser().getUserId();
        faceDraftDto.setUserId(userId);
        FaceDraft faceDraft = BeanUtil.copyProperties(faceDraftDto, FaceDraft.class);
        faceDraft.setCreateTime(new Date());
        faceDraft.setUpdateTime(new Date());
        faceDraftService.saveFaceDraft(faceDraft);

        return ServerResponseEntity.success();
    }

    /**
     * 更新草稿单
     */
    @PutMapping("/update")
    @Operation(summary = "更新草稿单" , description = "更新草稿单信息")
    public ServerResponseEntity<Void> update(@RequestBody FaceDraftDto faceDraftDto) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDraft existingDraft = faceDraftService.getById(faceDraftDto.getDraftId());
        if (existingDraft == null) {
            return ServerResponseEntity.showFailMsg("草稿单不存在");
        }
        if (!existingDraft.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限更新该草稿单");
        }

        // 将FaceDraftDto转换为FaceDraft实体
        FaceDraft faceDraft = BeanUtil.copyProperties(faceDraftDto, FaceDraft.class);
        faceDraft.setUpdateTime(new Date());
        faceDraftService.updateFaceDraft(faceDraft);
        return ServerResponseEntity.success();
    }

    /**
     * 删除草稿单
     */
    @DeleteMapping("/delete")
    @Operation(summary = "删除草稿单" , description = "根据草稿单ID删除")
    @Parameter(name = "draftId", description = "草稿单ID", required = true)
    public ServerResponseEntity<Void> delete(@RequestParam("draftId") Long draftId) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDraft existingDraft = faceDraftService.getById(draftId);
        if (existingDraft == null) {
            return ServerResponseEntity.showFailMsg("草稿单不存在");
        }
        if (!existingDraft.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限删除该草稿单");
        }

        faceDraftService.removeById(draftId);
        return ServerResponseEntity.success();
    }

    /**
     * 更新草稿单状态
     */
    @PostMapping("/updateStatus")
    @Operation(summary = "更新草稿单状态" , description = "更新草稿单状态")
    @Parameter(name = "draftId", description = "草稿单ID", required = true)
    @Parameter(name = "status", description = "状态（1:草稿, 2:已保存为设计稿）", required = true)
    public ServerResponseEntity<Void> updateStatus(
            @RequestParam("draftId") Long draftId,
            @RequestParam("status") Integer status) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDraft existingDraft = faceDraftService.getById(draftId);
        if (existingDraft == null) {
            return ServerResponseEntity.showFailMsg("草稿单不存在");
        }
        if (!existingDraft.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限更新该草稿单状态");
        }

        faceDraftService.updateStatus(draftId, status);
        return ServerResponseEntity.success();
    }

    /**
     * 获取草稿单数量
     */
    @GetMapping("/count")
    @Operation(summary = "获取草稿单数量" , description = "获取草稿单数量")
    @Parameter(name = "status", description = "状态（1:草稿, 2:已保存为设计稿）", required = false)
    public ServerResponseEntity<Integer> count(
            @RequestParam(value = "status", required = false) Integer status) {

        String userIdStr = SecurityUtils.getUser().getUserId();
        Integer count = faceDraftService.countByUserIdAndStatus(userIdStr, status);

        return ServerResponseEntity.success(count);
    }

    /**
     * 草稿转设计稿
     */
    @PostMapping("/convertToDesign")
    @Operation(summary = "草稿转设计稿" , description = "将草稿转为设计稿并设置排单状态为未排单")
    @Parameter(name = "draftId", description = "草稿单ID", required = true)
    public ServerResponseEntity<Void> convertToDesign(@RequestParam("draftId") Long draftId) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDraft existingDraft = faceDraftService.getById(draftId);
        if (existingDraft == null) {
            return ServerResponseEntity.showFailMsg("草稿单不存在");
        }
        if (!existingDraft.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限操作该草稿单");
        }

        faceDraftService.convertToDesign(draftId, userId);
        return ServerResponseEntity.success();
    }

    /**
     * 申请排单
     */
    @PostMapping("/applySchedule")
    @Operation(summary = "申请排单" , description = "用户申请排单，将排单状态改为待确认")
    @Parameter(name = "draftId", description = "草稿单ID", required = true)
    public ServerResponseEntity<Void> applySchedule(@RequestParam("draftId") Long draftId) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDraft existingDraft = faceDraftService.getById(draftId);
        if (existingDraft == null) {
            return ServerResponseEntity.showFailMsg("草稿单不存在");
        }
        if (!existingDraft.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限操作该草稿单");
        }

        faceDraftService.applySchedule(draftId, userId);
        return ServerResponseEntity.success();
    }

    /**
     * 获取排单状态列表
     */
    @GetMapping("/listByScheduleStatus")
    @Operation(summary = "获取排单状态列表" , description = "根据排单状态查询草稿单列表")
    @Parameter(name = "scheduleStatus", description = "排单状态（0:未排单,1:待确认排单,2:已确认排单,3:已生成订单）", required = false)
    public ServerResponseEntity<List<FaceDraftDto>> listByScheduleStatus(
            @RequestParam(value = "scheduleStatus", required = false) Integer scheduleStatus) {

        String userIdStr = SecurityUtils.getUser().getUserId();
        List<FaceDraft> faceDraftList = faceDraftService.listByScheduleStatus(userIdStr, scheduleStatus);
        List<FaceDraftDto> faceDraftDtoList = BeanUtil.copyToList(faceDraftList, FaceDraftDto.class);

        return ServerResponseEntity.success(faceDraftDtoList);
    }

    /**
     * 分页查询草稿单（带排单状态）
     */
    @GetMapping("/pageByStatus")
    @Operation(summary = "分页查询草稿单" , description = "分页查询草稿单，支持状态和排单状态筛选")
    @Parameter(name = "status", description = "状态（1:草稿, 2:已保存为设计稿）", required = false)
    @Parameter(name = "scheduleStatus", description = "排单状态（0:未排单,1:待确认排单,2:已确认排单,3:已生成订单）", required = false)
    public ServerResponseEntity<IPage<FaceDraftDto>> pageByStatus(
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "scheduleStatus", required = false) Integer scheduleStatus,
            PageParam<FaceDraft> page) {

        String userIdStr = SecurityUtils.getUser().getUserId();
        Long userId = Long.valueOf(userIdStr);
        IPage<FaceDraft> faceDraftPage = faceDraftService.pageByStatus(page, userId, 2, scheduleStatus);
        IPage<FaceDraftDto> faceDraftDtoPage = faceDraftPage.convert(faceDraft -> {
            FaceDraftDto faceDraftDto = BeanUtil.copyProperties(faceDraft, FaceDraftDto.class);
            return faceDraftDto;
        });

        return ServerResponseEntity.success(faceDraftDtoPage);
    }
}
